import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {Observable, of} from 'rxjs';
import {NavController} from '@ionic/angular';
import {HttpService} from '../services/http.service';
import {UrlAndOPT} from '../common/url-and-opt.enum';
import {AppConfig} from '../common/app-config.enum';
import {Storage} from '@ionic/storage';
import {mergeMap, switchMap} from 'rxjs/internal/operators';
import {fromPromise} from 'rxjs/internal/observable/fromPromise';

/**
 * 存管开户守卫
 */
@Injectable({
  providedIn: 'root'
})
export class UserAccountGuard implements CanActivate {

  constructor(
    private navCtrl: NavController,
    private storage: Storage,
    private service$: HttpService
  ) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.sureUserAccount((obj) => {
      if (obj[AppConfig.USER_ROLE_KEY]) { // 已开通
        console.log('已开通资金存管，角色：' + (obj[AppConfig.USER_ROLE_KEY] === 1 ? '出借人' : '借款人'));
        return fromPromise(this.storage.get(AppConfig.USER_INFO)) // 读取本地用户信息
          .pipe(
            mergeMap(userInfo => {
              return fromPromise(this.storage.set(AppConfig.USER_INFO, { // 更新本地用户信息
                ...userInfo,
                [AppConfig.USER_ROLE_KEY]: obj[AppConfig.USER_ROLE_KEY]
              }));
            }),
            switchMap(() => {
              this.goBack(); // 回退
              return of(false); // 不可进入
            })
          );
      } else { // 未开通，可以进入
        return of(true);
      }
    });
  }

  // 确认资金存管状态
  private sureUserAccount(callback): Observable<boolean> {
    return this.service$.doRequest(UrlAndOPT.auth_user_role)
      .pipe(
        mergeMap(callback)
      );
  }

  private goBack() {
    this.navCtrl.pop();
  }

}
